package com.szh.mysobproject.paging.source

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.szh.mysobproject.execption.ServiceException
import com.szh.mysobproject.model.RichList
import com.szh.mysobproject.viewmodel.app.UserNetwork
import timber.log.Timber

/**
 * @author : create by  szh
 * @date : 2022/7/13 9:36
 * @desc :富豪榜pagingSource
 */

class RichPagingSource : PagingSource<Int, RichList.RichUserItem>() {

    override fun getRefreshKey(state: PagingState<Int, RichList.RichUserItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RichList.RichUserItem> {
        return try {
            val page = params.key ?: FIRST_PAGE_INDEX
            Timber.d("load：===> page is $page")
            val response = UserNetwork.getRichList()
            val responseData = response.getData()
            val prevKey = null
            val nextKey = null
            if (response.isSuccess()) LoadResult.Page(
                data = responseData,
                prevKey = prevKey,
                nextKey = nextKey
            )
            else LoadResult.Error(ServiceException())
        } catch (t: Throwable) {
            t.printStackTrace()
            LoadResult.Error(t)
        }
    }

    companion object {
        private const val FIRST_PAGE_INDEX = 1
    }
}